<?php


use EasyWeChat\Factory;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Cache;

if (!function_exists('local_render_avatar')) {
    /**
     * @param string $value
     * @return string
     */
    function local_render_avatar($value = '')
    {
        return config('app.url') . '/' . $value;
    }
}

if (!function_exists('http_format')) {
    /**
     * @param $value
     * @return mixed|string
     */
    function http_format($value)
    {

        if (str_contains($value, 'http')) {
            return $value;
        } else {
            return 'http://' . $value;
        }
    }
}

if (!function_exists('generateTree')) {
    /**
     * 树形结构
     *
     * @param array $list
     * @param string $primary_key
     * @param string $parent_key
     * @param string $children_key
     * @return array
     */
    function generateTree(array $list, $primary_key = 'id', $parent_key = 'pid', $children_key = 'children')
    {

        if (count($list) == 0) {
            return [];
        }

        // 创建Tree
        $tree = [];

        // 创建基于主键的数组引用
        $refer = [];
        foreach ($list as $key => $data) {
            $refer[$data[$primary_key]] =& $list[$key];
        }

        //转出ID对内容
        foreach ($list as $key => $data) {
            unset($list[$key]['label']);
            // 判断是否存在parent
            $parentId = $data[$parent_key];
            if (0 == $parentId) {
                $tree[] =& $list[$key];
            } else {

                if (isset($refer[$parentId])) {

                    $parent =& $refer[$parentId];
                    $parent[$children_key][] =& $list[$key];

                } else {

                    $tree[] =& $list[$key];
                }
            }
        }

        return $tree;
    }
}


if (!function_exists('is_show_mobile_page')) {
    /**
     * @return bool
     */
    function is_show_mobile_page()
    {
        if (empty($_SERVER['HTTP_USER_AGENT'])) {
            return false;
        }
        $_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : '';
        $mobile_browser = '0';
        if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i', strtolower($_SERVER['HTTP_USER_AGENT'])))
            $mobile_browser++;
        if ((isset($_SERVER['HTTP_ACCEPT'])) and (strpos(strtolower($_SERVER['HTTP_ACCEPT']), 'application/vnd.wap.xhtml+xml') !== false))
            $mobile_browser++;
        if (isset($_SERVER['HTTP_X_WAP_PROFILE']))
            $mobile_browser++;
        if (isset($_SERVER['HTTP_PROFILE']))
            $mobile_browser++;

        $mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4));
        $mobile_agents = array(
            'w3c ', 'acs-', 'alav', 'alca', 'amoi', 'audi', 'avan', 'benq', 'bird', 'blac',
            'blaz', 'brew', 'cell', 'cldc', 'cmd-', 'dang', 'doco', 'eric', 'hipt', 'inno',
            'ipaq', 'java', 'jigs', 'kddi', 'keji', 'leno', 'lg-c', 'lg-d', 'lg-g', 'lge-',
            'maui', 'maxo', 'midp', 'mits', 'mmef', 'mobi', 'mot-', 'moto', 'mwbp', 'nec-',
            'newt', 'noki', 'oper', 'palm', 'pana', 'pant', 'phil', 'play', 'port', 'prox',
            'qwap', 'sage', 'sams', 'sany', 'sch-', 'sec-', 'send', 'seri', 'sgh-', 'shar',
            'sie-', 'siem', 'smal', 'smar', 'sony', 'sph-', 'symb', 't-mo', 'teli', 'tim-',
            'tosh', 'tsm-', 'upg1', 'upsi', 'vk-v', 'voda', 'wap-', 'wapa', 'wapi', 'wapp',
            'wapr', 'webc', 'winw', 'winw', 'xda', 'xda-'
        );
        if (in_array($mobile_ua, $mobile_agents))
            $mobile_browser++;
        if (strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false)
            $mobile_browser++;
        // Pre-final check to reset everything if the User is on Windows
        if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') !== false)
            $mobile_browser = 0;
        // But WP7 is also Windows, with a slightly different characteristic
        if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') !== false)
            $mobile_browser++;
        if ($mobile_browser > 0)
            return true;
        else
            return false;
    }
}

/**
 * @param $multiple
 * @param $type
 * @return float|int|mixed
 */
function generateCacheTtl($multiple, $type)
{
    switch ($type) {
        case "minute":
            $time = $multiple * 60;
            break;
        case "hour":
            $time = $multiple * 60 * 60;
            break;
        default:
            // 默认秒
            $time = $multiple;
            break;
    }
    // 随机增加
    return $time + rand(5, 200);
}


if (!function_exists('get_upload_path')) {
    /**
     * 文件上传
     */
    function get_upload_path($key, $type = 'local')
    {
        // 如果没有 $Key
        if (empty($key)) return '';

        if (!in_array($type,config('Uploads.TYPE'))) {
            return '图片地址不存在';
        }
        // 如果 $Key 包含了 http等 是一个完整的地址，直接返回
        if (strpos($key, 'http://')  !== false
            || strpos($key, 'https://')  !== false
            || strpos($key,'data:image') !== false) {
            return $key;
        }

        if($type == 'Kodo') {
            $key = config('Uploads.Kodo') . $key;
        }
        if($type == 'OSS') {
            $key = config('Uploads')['OSS']['bucket_url'] . '/' . $key;
        }
        if($type == 'COS') {
            $key = config('Uploads.COS') . $key;
        }

        return $key;
    }
}


if (!function_exists('get_upload_paths')) {
    function get_upload_paths($keys)
    {
        $urls = [];
        if(is_array($keys)){
            foreach ($keys as $key){
                array_push($urls,get_upload_path($key));
            }
        }
        return $urls;
    }
}

    /**
     * 获取系统配置
     */
if(!function_exists('system_config')){
    function system_config($name){
        if(empty($name)){
            return [];
        }
        $systemConfigTable = \App\Models\SystemConfigTable::where('english_name',$name)->firstOrFail();
        if (empty($systemConfigTable)){
            return [];
        }
        $systemConfigs = $systemConfigTable->systemConfig;
        $data = $systemConfigs->mapWithKeys(function ($item) {
            return [$item->menu_name => $item->value];
        });
        return $data;
    }
}

if(!function_exists('getApp')) {
    function getApp()
    {
        //获取config配置appId 和secret 和 token 和 aes_key
        $config = config('wechat.official_account.default');
        $config = $config + $default_config = config('wechat.defaults');

        return Factory::officialAccount($config);
    }
}


/**
 * 渲染oss
 */
if (!function_exists('render')) {
    function render($file)
    {
        return  config('filesystems.disks.oss.bucket_url') . '/' . $file;
    }
}

if (!function_exists('route_parameter')) {
    /**
     * 从路由中获取给定参数。
     *
     * @param $name
     * @param null $default
     * @return mixed
     */
    function route_parameter($name, $default = null)
    {
        //app 方法将返回 服务容器 实例
        $routeInfo = app('request')->route($name);

        if(empty($routeInfo)){
            return $default;
        }
        return $routeInfo;
    }
}


/**
 * 根据name获取category_group_id
 *
 * @param $name
 */
if (!function_exists('getCategoryGroupIdByName')) {
    function getCategoryGroupIdByName($name)
    {
        //首先获取缓存中的类组
        $groups = Cache::get('category_group');
        if (empty($groups)) {
            /**
             *有时，你可能想要在 CLI 以外运行 Artisan 命令。例如，你可能在一个路由或控制器中运行一个 Artisan 命令。
             *你可以使用 Artisan 门面的 call 方法来实现之。
             * call 方法的第一个参数为命令的名称或类名，第二个参数为数组形式的命令参数
             */
            //需要提前设置好，自定义的artisan命令
            \Illuminate\Support\Facades\Artisan::call('cache:category_group');
            //相当于运行php artisan cache:category_group
        }

        $groups = Cache::get('category_group');

        if (empty($groups)) {
            return null;
        }
        //data_get函数 从多维数组或对象中根据指定键检索值,参数1：数组或对象，参数2：指定的键，参数3：默认值
       return data_get($groups, $name, null);
    }
}

//对象转数组
function objectToArray($object)
{
    //先编码成json字符串，再解码成数组
    return json_decode(json_encode($object), true);
}

/**
 * @param $key
 * @param null $m_id
 * @param mixed ...$args
 */
function generateConfigCacheKey($key, $m_id = null, ...$args)
{
    $cache_key = config('cache_keys.' . $key);

    if (empty($cache_key)) {
        throw  new InvalidArgumentException('参数错误: ' . $key . ' 不存在');
    }

    if (empty($m_id)) {
        return $cache_key;
    }

    return generateCacheKey($cache_key, $m_id, ...$args);
}

/**
 * 生成缓存key
 *
 * @param array $args
 * @return void
 */
function generateCacheKey(...$args)
{
    $params = [];

    foreach ($args as $arg) {
        $params[] = strtoupper($arg);
    }

    return implode('::', $params);
}



if (!function_exists('get_user_info')) {
    /**
     * 获取当前登录用户信息
     */
    function get_user_info($field = null)
    {
        $user = auth('web')->user();

        if (empty($field)) {
            return $user;
        }

        return $user->{$field};
    }
}

  //缓存城市数据
 if (!function_exists('cache_city')){
     function cache_city($pid = 0 ){

         return Cache::rememberForever('cache_city'.$pid,function () use($pid){
            return \App\Models\City::query()
                ->select('id','name')
                ->with(['children'=>function($query){
                    $query->where('level',2)->with('children');
                }])
                ->where('pid',$pid)
                ->get()
                ->keyBy('id');
         });
     }
 }

if (!file_exists('forget_city_cache')){
    //缓存所有的分类
    function forget_city_cache(){
        //清空缓存
      return Cache::forget('cache_city');


    }






}



